package com.wu.cloud.custom.controller;

import bean.PeskResponseEntity;
import com.wu.cloud.custom.entity.UserTokenEntity;
import com.wu.cloud.custom.util.HttpComponent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import util.ResponseUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * @author xwu36
 */
@RestController
public class TokenController {

    static final Logger logger = LoggerFactory.getLogger(TokenController.class);

    @Autowired
    @Qualifier("pesk_template")
    RestTemplate restTemplate;
    @Autowired
    HttpComponent httpComponent;


    private static final String CLIENT_ID = "self_app";
    private static final String CLIENT_SECRET = "123456";
    private static final String GRANT_TYPE = "authorization_code";
    private static final String REDIRECT_URL = "http://127.0.0.1:9091/auth/code";
    private static final String REQUEST_AUTH_URL = "http://127.0.0.1:8085/oauth/token";

    @RequestMapping("/auth/code")
    public PeskResponseEntity getToken(@RequestParam String code) {

        PeskResponseEntity responseEntity = null;
        //请求参数
        Map<String, Object> params = new HashMap<>(5);
        params.put("client_id", CLIENT_ID);
        params.put("client_secret", CLIENT_SECRET);
        params.put("grant_type", GRANT_TYPE);
        params.put("code", code);
        params.put("redirect_uri", REDIRECT_URL);
        //判断返回结果
        String url = REQUEST_AUTH_URL + "?" + httpComponent.mapToParam(params);
        UserTokenEntity userTokenEntity = restTemplate.getForObject(url, UserTokenEntity.class);
        Assert.notNull(userTokenEntity, "User Token is null");
        return ResponseUtil.success(userTokenEntity);
    }
}
